package com.geline.mybatisplus.context;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.geline.mybatisplus.annotation.ExtractTable;
import com.geline.mybatisplus.domain.ExtractSchema;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mx
 * @date 2025/9/26
 */
@Slf4j
public class ExtractTableHelper {

    private static List<ExtractSchema> extractSchemas = new ArrayList<>();

    public static void init() {
        List<TableInfo> tableInfos = TableInfoHelper.getTableInfos();
        for (TableInfo tableInfo : tableInfos){
            Class<?> entityType = tableInfo.getEntityType();
            TableName annotation = entityType.getAnnotation(TableName.class);
            String idName = getIdFieldName(entityType);
            ExtractTable[] extractTables = entityType.getAnnotationsByType(ExtractTable.class);
            if(extractTables!=null && extractTables.length>0){
                for (ExtractTable extractTable : extractTables){
                    ExtractSchema schema = new ExtractSchema(annotation.value(), idName, extractTable.value(), extractTable.foreignKey());
                    extractSchemas.add(schema);
                }
            }
        }
        log.info(">>>> find @ExtractTable size = {}", extractSchemas.size());
    }

    public static ExtractSchema getExtractSchema(String mainTable, String subTable) {
        for (ExtractSchema extractSchema : extractSchemas) {
            if (extractSchema.getTable().equals(subTable) && extractSchema.getForeignTable().equals(mainTable)) {
                return extractSchema;
            }
        }
        return null;
    }

    public static String getForeignKey(String mainTable, String subTable) {
        ExtractSchema extractSchema = getExtractSchema(mainTable, subTable);
        return extractSchema.getForeignKey();
    }

    private static String getIdFieldName(Class entityClass){
        for(Field field : entityClass.getDeclaredFields()){
            TableId tableId = field.getAnnotation(TableId.class);
            if(tableId!=null){
                return field.getName();
            }
        }
        return "id";
    }
}
